﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;
using StyleMVVM.DependencyInjection;
using StyleMVVM.DependencyInjection.Impl;

namespace StyleMVVM.BootstrapperHelpers
{
	public sealed class ClientBaseActivationStrategyFactory : IExportStrategyFactory
	{
		public IExportStrategy CreateStrategy(IDependencyInjectionContainer container,
														  Type type,
														  IEnumerable<object> attributes,
														  bool alreadyExported)
		{
			IExportStrategy returnValue = null;

			if (!alreadyExported)
			{
				Type baseType = type.GetTypeInfo().BaseType;

				if (baseType != null &&
					 baseType.IsConstructedGenericType &&
					 baseType.GetGenericTypeDefinition() == typeof(ClientBase<>))
				{
					returnValue = new AttributedExportStrategy(new[] { baseType.GenericTypeArguments[0].FullName }, type);

					returnValue.DisposalCleanupDelegate =
						disposed =>
						{
							ICommunicationObject communicationObject = (ICommunicationObject)disposed;

							if (communicationObject.State == CommunicationState.Faulted)
							{
								communicationObject.Abort();
							}
							else
							{
								communicationObject.Close();
							}
						};
				}
			}

			return returnValue;
		}
	}
}